package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.dto.PageUserTokenBeanDTO;
import com.yuanfeng.commoms.dto.job.ShopSettleAccountInfoDTO;
import com.yuanfeng.commoms.dto.userms.UserTokenBeanDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.excel.Constants;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.order.OrderBaseVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.dto.FinancialSettlementDTO;
import com.yuanfeng.order.dto.WaitOrderDTO;
import com.yuanfeng.order.entity.OrderSettlementEntity;
import com.yuanfeng.order.feign.PayMentServiceClient;
import com.yuanfeng.order.mapper.OrderBaseMapper;
import com.yuanfeng.order.mapper.OrderSettlementMapper;
import com.yuanfeng.order.service.OrderSettlementService;
import com.yuanfeng.order.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class OrderSettlementServiceImpl extends ServiceImpl<OrderSettlementMapper, OrderSettlementEntity>
    implements OrderSettlementService{

    @Resource
    private OrderBaseMapper orderBaseMapper;
    @Resource
    private PayMentServiceClient payMentServiceClient;
    @Override
    public ResponseResult exportExcel(Map<String, Object> paraMap, HttpServletResponse response) throws IOException, ParseException {
        @SuppressWarnings("resource")
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        Integer pageSize= (Integer)paraMap.get("pageSize");
        Integer currentPage =((Integer) paraMap.get("limit")-1) * pageSize;
        paraMap.put("page",  pageSize);
        paraMap.put("limit", currentPage);
        OrderSettlementEntity orderSettlement = this.baseMapper.selectById(paraMap.get("orderSettlementId").toString());
        if (orderSettlement.getOsDate() == null) {
            paraMap.put("osStartDate", orderSettlement.getOsStartDate());
            paraMap.put("osEndDate", orderSettlement.getOsEndDate());
            paraMap.remove("orderSettlementId");
        }
        paraMap.put("shopId", orderSettlement.getShopId());
        String osDatetime = DateUtils.dateConvert(orderSettlement.getOsDatetime().toString()).split(" ")[0];
        paraMap.put("osDatetime", osDatetime);
        List<OrderBaseVO> listOrderBase;
        IPage<OrderBaseVO> page;
        if(orderSettlement.getOsOrderType().equals("3")){
             page=orderBaseMapper.listSupplyBaseInfo(new Query<OrderBaseVO>().getPage(paraMap),
                     paraMap);
        }else if (orderSettlement.getOsOrderType().equals("2")) {
             page=orderBaseMapper.listDealerBaseInfo(new Query<OrderBaseVO>().getPage(paraMap),
             paraMap);
        }else{

             page=orderBaseMapper.listBaseInfo(new Query<OrderBaseVO>().getPage(paraMap),
             paraMap);
            for (OrderBaseVO orderBaseInfo : page.getRecords()) {
                BigDecimal b1 = new BigDecimal(orderBaseInfo.getOrderPaymentAmount().toString());
                BigDecimal b2 = new BigDecimal(orderBaseInfo.getOrderSupplyAmount().toString());
                orderBaseInfo.setOrderPaymentAmount(b1.subtract(b2));
            }
        }
        //设置要导出的文件的名字
        String fileName = "XiangQingExcel" +System.currentTimeMillis()+ ".csv";
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = {"订单编号", "订单金额(不含运费)", "红包金额", "运费", "佣金", "分享佣金", "推广佣金", "会员折扣",
                "经销折扣", "供货价", "下单日期", "成交日期", "买家"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (OrderBaseVO orderBaseInfo : page.getRecords()) {
            String OrderCreateTime = DateUtils.dateConvert(orderBaseInfo.getOrderCreateTime().toString());
            String OrderFinishedTime = DateUtils.dateConvert(orderBaseInfo.getOrderFinishedTime().toString());
            HSSFRow rowContent = sheet.createRow(rowNum);
            //订单编号
            rowContent.createCell(0).setCellValue(orderBaseInfo.getOrderId());
            //订单金额 (不含运费)（元）
            rowContent.createCell(1).setCellValue(orderBaseInfo.getOrderPaymentAmount().doubleValue());
            //红包金额
            rowContent.createCell(2).setCellValue(orderBaseInfo.getOrderRptPrice());
            //运费
            rowContent.createCell(3).setCellValue(orderBaseInfo.getOrderShippingFee());
            //佣金
            rowContent.createCell(4).setCellValue(orderBaseInfo.getOrderCommissionFee());
            //分享佣金
            rowContent.createCell(5).setCellValue(orderBaseInfo.getFxCommission());
            //推广佣金
            rowContent.createCell(6).setCellValue(orderBaseInfo.getTgCommission());
            //会员折扣
            rowContent.createCell(7).setCellValue(orderBaseInfo.getBaseMemberDiscount());
            //经销折扣
            rowContent.createCell(8).setCellValue(orderBaseInfo.getOrderDiscountFee().doubleValue());
            //供货价
            rowContent.createCell(9).setCellValue(orderBaseInfo.getGoodsPriceSum());
            //下单日期
            rowContent.createCell(10).setCellValue(OrderCreateTime);
            //成交日期
            rowContent.createCell(11).setCellValue(OrderFinishedTime);
            //买家
            rowContent.createCell(12).setCellValue(orderBaseInfo.getBuyerUserName());

            rowNum++;
        }

        try {
            FileOutputStream output = new FileOutputStream(ResourceUtils.getURL("classpath:").getPath() + "/static/" + fileName);
            workbook.write(output);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(Constants.PLATFORM_URL + fileName);
    }

    @Override
    public ResponseResult getMerchantAmountExp(FinancialSettlementDTO param) {
        if (param.getStartTime() == "" && param.getEndTime() == "") {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String finishTime = dateformat.format(new Date());
            param.setEndTime(finishTime);
            param.setStartTime("2017-01-01");
        }
        List<FinancialSettlementDTO> financialList = this.baseMapper.getMerchantAmountExp(param);

        String[] title = {"店铺名", "订单总额", "退单总额", "红包总额", "退还红包总额", "罚款总额", "提现总额", "未提现总额","未结算金额"};

        List<Map<String, String>> list = Lists.newArrayList();

        for (FinancialSettlementDTO res : financialList) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            // 订单状态 1.待付款 2.已付款 3.待发货 4.已发货 5.已签收 6.确认收货 7.取消 8.退款中 9.已退款 11.待自提',
            map.put("店铺名", res.getShopName());
            map.put("订单总额", res.getOsAmount() + "");
            map.put("退单总额", res.getOsOrderReturnAmount() + "");
            map.put("红包总额", res.getOsRedpacketAmount() + "");
            map.put("退还红包总额", res.getOsRedpacketReturnAmount() + "");
            map.put("罚款总额", res.getOsFineAmount() + "");
            map.put("提现总额", res.getWithdrawalAmount() + "");
            map.put("未提现总额", res.getUndrawnAmount() + "");
            map.put("未结算金额", res.getNotSettlementMoney() + "");
            list.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(title, map,
                new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult businessList(Map<String, String> paraMap) {
        String tokenString = paraMap.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(tokenString);
        paraMap.put("shopId", userInfo.getShopId());
        if (userInfo.getShopType() == 1) {
            // 商家需要根据结算类型查询  自销和经销结算
            paraMap.put("osOrderType", StringUtils.isBlank(paraMap.get("osOrderType")) ? "1" : paraMap.get("osOrderType"));
        } else {
            //供应商
            paraMap.put("osOrderType", "3");
        }
        Page<OrderSettlementVO> page = new Page<>(Integer.parseInt(paraMap.get("page")), Integer.parseInt(paraMap.get("limit")));
        IPage<OrderSettlementVO> result = this.baseMapper.businessList(page, paraMap);
        return ResponseResult.success(PageUtils.getPage(result));
    }

    @Override
    public ResponseResult exportexcelSettlementBusiness(Map<String, String> paraMap) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        String tokenString = paraMap.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(tokenString);
        paraMap.put("shopId", userInfo.getShopId());
        if (userInfo.getShopType().intValue() == 1) {
            // 商家需要根据结算类型查询  自销和经销结算
            paraMap.put("osOrderType", StringUtils.isBlank(paraMap.get("osOrderType")) ? "1" : paraMap.get("osOrderType"));
        } else {
            paraMap.put("osOrderType", null);
        }
        List<OrderSettlementVO> listSettlement = this.baseMapper.exportexcelSettlementBusiness(paraMap);
        // 设置要导出的文件的名字
        String fileName = userInfo.getShopId() + ".xls";
        // 新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = {"序号", "店铺名称", "结算单号", "开始时间", "结束时间", "本期应收", "订单金额", "红包金额", "退还红包金额", "佣金金额", "退还佣金金额",
                "退单金额", "结算状态"};
        // headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        // 在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 在表中存放查询到的数据放入对应的列
        for (OrderSettlementVO orderSettlement : listSettlement) {
            String osState = orderSettlement.getOsState();
            String state = null;
            if ("1".equals(osState)) {
                state = "已出账";
            } else if ("2".equals(osState)) {
                state = "商家已确认";
            } else if ("3".equals(osState)) {
                state = "平台已审核";
            } else if ("4".equals(osState)) {
                state = "结算完成";
            } else {
                state = "已提现";
            }
            orderSettlement.setOsState(state);
            HSSFRow rowContent = sheet.createRow(rowNum);
            // 序号
            rowContent.createCell(0).setCellValue(rowNum);
            // 商家名称
            rowContent.createCell(1).setCellValue(orderSettlement.getShopName());
            // 订单编号
            rowContent.createCell(2).setCellValue(orderSettlement.getOsId());
            // 开始日期
            rowContent.createCell(3).setCellValue(orderSettlement.getOsStartDate());
            // 结束日期
            rowContent.createCell(4).setCellValue(orderSettlement.getOsEndDate());
            // 本期应结
            rowContent.createCell(5).setCellValue(orderSettlement.getOsAmount());
            // 订单金额
            rowContent.createCell(6).setCellValue(orderSettlement.getOsOrderAmount());
            // 红包
            rowContent.createCell(7).setCellValue(orderSettlement.getOsRedpacketAmount());
            // 退还红包金额
            rowContent.createCell(8).setCellValue(orderSettlement.getOsRedpacketReturnAmount());
            // 收取佣金
            rowContent.createCell(9).setCellValue(orderSettlement.getOsCommisAmount());
            // 退还佣金
            rowContent.createCell(10).setCellValue(orderSettlement.getOsCommisReturnAmount());
            // 退单金额
            rowContent.createCell(11).setCellValue(orderSettlement.getOsOrderReturnAmount());
            // 账单状态
            rowContent.createCell(12).setCellValue(orderSettlement.getOsState());

            rowNum++;
        }
        try {
            FileOutputStream output = new FileOutputStream(
                    ResourceUtils.getURL("classpath:").getPath() + "/static/" + fileName);
            workbook.write(output);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(Constants.PLATFORM_URL + fileName);
    }

    @Override
    public ResponseResult settlementDetail(Map<String, String> paraMap) {
        OrderSettlementVO orderSettlement = this.baseMapper.settlementDetail(paraMap);
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("osId", orderSettlement.getOsId());
        returnMap.put("shopName", orderSettlement.getShopName());
        returnMap.put("date", orderSettlement.getOsStartDate().toString() + " 至  " + orderSettlement.getOsEndDate().toString());
        returnMap.put("osDatetime", orderSettlement.getOsDatetime());
        String osAmountDetail = null;
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));

        if(orderSettlement.getOsOrderType().equals("4")){
            osAmountDetail= orderSettlement.getOsAmount() + " = " +orderSettlement.getOsCommisAmount()
                    + "(佣金金额) - " + orderSettlement.getOsCommisReturnAmount() + "(退还佣金)";
        } else if (userInfo.getShopType() == 1) {
            // 商家中心
            // 商家经销结算单
            if (orderSettlement.getOsOrderType().equals("2")) {
                //订单金额（不含运费）-供货价-抽佣+会员折扣+退还抽佣-退单金额（不含运费）+供货价-退还会员折扣
                osAmountDetail = orderSettlement.getOsAmount() + " = "
                        + orderSettlement.getOsOrderAmount() + "(订单金额 不含运费) - "
                        + orderSettlement.getOsSupplyPrice() + "(供货价) - "
                        + orderSettlement.getOsCommisAmount() + "(佣金金额) + "
                        + orderSettlement.getOsBaseMemberDiscount() + "(会员折扣) + "
                        + orderSettlement.getOsCommisReturnAmount() + "(退还佣金) - "
                        + orderSettlement.getOsOrderReturnAmount() + "(退单金额) + "
                        + orderSettlement.getOsReturnSupplyPrice() + "(退还供货价) - "
                        + orderSettlement.getOsReturnMemberDiscount() + "(退还会员折扣)";
            } else {
                BigDecimal osAmount = new BigDecimal(orderSettlement.getOsOrderAmount());
                osAmountDetail = orderSettlement.getOsAmount() + " = " + osAmount + "(订单金额)" + " + "
                        + orderSettlement.getOsRedpacketAmount() + "(红包金额) - " + orderSettlement.getOsCommisAmount()
                        + "(佣金金额) + "+ orderSettlement.getOsBaseMemberDiscount() + "(会员折扣) - "
                        + orderSettlement.getOsOrderReturnAmount() + "(退单金额) - "
                        + orderSettlement.getOsRedpacketReturnAmount() + "(退还红包金额) + "
                        + orderSettlement.getOsCommisReturnAmount() + "(退还佣金) + "
                        + orderSettlement.getOsShippingAmount() + "(运费) - "
                        + orderSettlement.getOsReturnMemberDiscount() + "(退还会员折扣) - "
                        + orderSettlement.getOsTgCommission() + "(推广佣金) - "
                        + orderSettlement.getOsFxCommission() + "(分享佣金) ";
            }
        } else {
            // 供应商结算单
            osAmountDetail = orderSettlement.getOsAmount() + " = " + orderSettlement.getOsOrderAmount() + "(供货价 不含运费) -"
                    + orderSettlement.getOsCommisAmount() + "(佣金金额) -"
                    + orderSettlement.getOsOrderReturnAmount() + "(退还供货价) +  "
                    + orderSettlement.getOsCommisReturnAmount() + "(退还佣金) + "
                    + orderSettlement.getOsShippingAmount() + "(运费)" ;
        }
        returnMap.put("osAmountDetail", osAmountDetail);
        returnMap.put("osState", orderSettlement.getOsState());
        returnMap.put("osAmount", orderSettlement.getOsAmount());
        return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult listBaseInfo(Map<String, Object> paraMap) {
        OrderSettlementVO orderSettlement = this.baseMapper.getSettlementDate(paraMap);
        // 如果时间在 2019-01-28 之前，则需要这个时间
        if (StringUtils.isBlank(orderSettlement.getOsDate())) {
            try {
                paraMap.put("osStartDate", DateUtils.dateConvert(orderSettlement.getOsStartDate().toString()));
                paraMap.put("osEndDate", DateUtils.dateConvert(orderSettlement.getOsEndDate().toString()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            paraMap.remove("orderSettlementId");
        }
        paraMap.put("shopId", orderSettlement.getShopId());
        paraMap.put("osDatetime", orderSettlement.getOsDate());
        IPage<OrderBaseInfoVO> listOrderBase;
        if (orderSettlement.getOsOrderType().equals("3")) {
            // 代发货订单供应商结算数据
            listOrderBase = this.baseMapper.listSupplyBaseInfo(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
        } else if (orderSettlement.getOsOrderType().equals("4")) {
            listOrderBase = this.baseMapper.listBaseInfo2(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
        }else if (orderSettlement.getOsOrderType().equals("2")) {
            listOrderBase = this.baseMapper.listDealerBaseInfo(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
        } else {
            listOrderBase = this.baseMapper.listBaseInfo(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
            for (OrderBaseInfoVO orderBaseInfo : listOrderBase.getRecords()) {
                BigDecimal b1 = new BigDecimal(orderBaseInfo.getOrderPaymentAmount().toString());
                BigDecimal b2 = new BigDecimal(orderBaseInfo.getOrderSupplyAmount().toString());
                orderBaseInfo.setOrderPaymentAmount(b1.subtract(b2).doubleValue());
            }
        }
        return ResponseResult.success(PageUtils.getPage(listOrderBase));
    }

    @Override
    public ResponseResult listReutrnOrder(Map<String, Object> paraMap) {
        OrderSettlementVO orderSettlement = this.baseMapper.getSettlementDate(paraMap);
        if (StringUtils.isBlank(orderSettlement.getOsDate())) {
            try {
                paraMap.put("osStartDate", DateUtils.dateConvert(orderSettlement.getOsStartDate().toString()));
                paraMap.put("osEndDate", DateUtils.dateConvert(orderSettlement.getOsEndDate().toString()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            paraMap.remove("orderSettlementId");
            paraMap.put("returnShopHandle", "returnShopHandle");
        }
        paraMap.put("shopId", orderSettlement.getShopId());
        paraMap.put("osDatetime", orderSettlement.getOsDate());

        IPage<ReturnOrderDetailListVO> listOrderBase;
        if (orderSettlement.getOsOrderType().equals("3")) {
            listOrderBase = this.baseMapper.listSupplyReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap),paraMap);
        } else if (orderSettlement.getOsOrderType().equals("4")) {
            listOrderBase = this.baseMapper.listReutrnOrder2(new Query<ReturnOrderDetailListVO>().getPage(paraMap),paraMap);
        } else if (orderSettlement.getOsOrderType().equals("2")) {
            listOrderBase = this.baseMapper.listDealerReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap),paraMap);
        }else {
            listOrderBase = this.baseMapper.listReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap),paraMap);
        }
        return ResponseResult.success(PageUtils.getPage(listOrderBase));
    }

    @Override
    public ResponseResult exportexcelSettlementBaseInfo(Map<String, Object> paraMap) {
        OrderSettlementVO orderSettlement = this.baseMapper.getSettlementDate(paraMap);
        // 如果时间在 2019-01-28 之前，则需要这个时间
        if (StringUtils.isBlank(orderSettlement.getOsDate())) {
            try {
                paraMap.put("osStartDate", DateUtils.dateConvert(orderSettlement.getOsStartDate().toString()));
                paraMap.put("osEndDate", DateUtils.dateConvert(orderSettlement.getOsEndDate().toString()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            paraMap.remove("orderSettlementId");
        }
        paraMap.put("shopId", orderSettlement.getShopId());
        paraMap.put("osDatetime", orderSettlement.getOsDate());
        List<OrderBaseInfoVO> listBaseInfo;
        if (orderSettlement.getOsOrderType().equals("3")) {
            listBaseInfo = this.baseMapper.listSupplyBaseInfoExport(paraMap);
        } else {
            listBaseInfo = this.baseMapper.listBaseInfoExport(paraMap);
        }
        // 设置要导出的文件的名字
        String fileName = paraMap.get("shopName") + "订单" + ".xls";
        String[] title = {"订单编号", "订单金额", "供货价", "红包金额", "运费", "佣金", "下单日期", "成交日期", "买家"};
        List<Map<String, String>> list = Lists.newArrayList();
        // 在表中存放查询到的数据放入对应的列
        for (OrderBaseInfoVO orderBaseInfo : listBaseInfo) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            map.put("订单编号", orderBaseInfo.getOrderId());
            map.put("订单金额", orderBaseInfo.getOrderPaymentAmount() + "");
            map.put("供货价", null == orderBaseInfo.getOrderSupplyAmount() ? "0.00" : orderBaseInfo.getOrderSupplyAmount() + "");
            map.put("红包金额", orderBaseInfo.getOrderRptPrice() + "");
            map.put("运费", orderBaseInfo.getOrderShippingFee() + "");
            map.put("佣金", orderBaseInfo.getOrderCommissionFee() + "");
            map.put("下单日期", orderBaseInfo.getOrderCreateTime());
            map.put("成交日期", orderBaseInfo.getOrderFinishedTime());
            map.put("买家", orderBaseInfo.getBuyerUserName());
            list.add(map);
        }

        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put(fileName, list);
        String url = ExcelsUtil.createExcel(title, map,
                new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult exportexcelSettlementReturnOrder(Map<String, Object> paraMap) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        OrderSettlementVO orderSettlement = this.baseMapper.getSettlementDate(paraMap);
        List<ReturnOrderDetailListVO> listReutrnOrderExport;
        if (orderSettlement.getOsOrderType().equals("3")) {
            listReutrnOrderExport = this.baseMapper.listSupplyReutrnOrderExport(paraMap);
        } else {
            listReutrnOrderExport = this.baseMapper.listReutrnOrderExport(paraMap);
        }
        // 设置要导出的文件的名字
        String fileName = paraMap.get("shopName") + "退单" + ".xls";
        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        String[] headers = {"订单编号", "退款金额", "供货价", "退还佣金", "退款理由", "退款时间", "买家"};
        // headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        // 在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 在表中存放查询到的数据放入对应的列
        for (ReturnOrderDetailListVO returnOrderDetail : listReutrnOrderExport) {
            HSSFRow rowContent = sheet.createRow(rowNum);
            // 订单编号
            rowContent.createCell(0).setCellValue(returnOrderDetail.getOrderId());
            // 退款金额
            rowContent.createCell(1).setCellValue(returnOrderDetail.getReturnCash());
            // 供货金额
            rowContent.createCell(2).setCellValue(null == returnOrderDetail.getOrderSupplyAmount() ? 0.00 : returnOrderDetail.getOrderSupplyAmount());
            // 退还佣金
            rowContent.createCell(3).setCellValue(returnOrderDetail.getReturnCommisionFee());
            // 退款理由
            rowContent.createCell(4).setCellValue(returnOrderDetail.getReturnReason());
            // 退款时间
            rowContent.createCell(5).setCellValue(returnOrderDetail.getReturnAddTime());
            // 买家
            rowContent.createCell(6).setCellValue(returnOrderDetail.getBuyerUserAccount());

            rowNum++;
        }

        try {
            FileOutputStream output = new FileOutputStream(
                    ResourceUtils.getURL("classpath:").getPath() + "/static/" + fileName);
            workbook.write(output);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(Constants.PLATFORM_URL + fileName);
    }

    @Override
    public ResponseResult waitSettlement(UserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        // 平台应付金额 =订单金额 + 红包金额 - 佣金金额 - 退单金额 - 退还红包金额 + 退还佣金-罚款金额
        WaitSettlementVO result = new WaitSettlementVO();
        StringBuilder osAmountStr = new StringBuilder();
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(shopId,1);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        // 获取单个店铺所有未结算的订单金额
        ShopSettleAccountInfoDTO orderSettleAccountOrder = this.baseMapper.getSettleAccountOrder(shopId, 2,dBefore);
        // 获取单个店铺所有未结算的退单金额
        ShopSettleAccountInfoDTO returnSettleAccountOrder = this.baseMapper.getSettleAccountReturn(shopId, 2,dBefore);
        if(null == orderSettleAccountOrder){
            orderSettleAccountOrder = new ShopSettleAccountInfoDTO();
        }

        if(null == returnSettleAccountOrder){
            returnSettleAccountOrder = new ShopSettleAccountInfoDTO();
        }
        // 获取单个店铺的 罚款金额,处罚时间大于72小时
        Double fineMoney = this.baseMapper.getFineMoneyByShopId(shopId);
        Double totalAmount = 0.00;
        // 1、没有订单没有退单
        if (null == orderSettleAccountOrder && null == returnSettleAccountOrder) {
            totalAmount = totalAmount - fineMoney;
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ").append(0.00).append("(订单金额 不含运费) + ").append(0.00).append("(红包金额) - ")
                    .append(0.00).append("(佣金金额) + ").append(0.00).append("(会员折扣) - ").append(0.00).append("(退单金额) - ").append(0.00)
                    .append("(退还红包金额) + ").append(0.00).append("(退还佣金) + ")
                    .append(0.00).append("(运费) - ").append(0.00).append("(退还会员折扣) - ")
                    .append(0.00).append("(推广佣金) - ")
                    .append(0.00).append("(分享佣金)");
        }

        // 2、有订单没有退单的情况
        if (null != orderSettleAccountOrder && null == returnSettleAccountOrder) {
            totalAmount = totalAmount +orderSettleAccountOrder.getOrderPaymentAmount()+orderSettleAccountOrder.getOrderRptPrice()
                    - orderSettleAccountOrder.getOrderCommissionFee() + orderSettleAccountOrder.getBaseMemberDiscount()
                    - orderSettleAccountOrder.getTgCommission() - orderSettleAccountOrder.getFxCommission();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ").append(new BigDecimal(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                    .append("(订单金额 不含运费) + ").append(orderSettleAccountOrder.getOrderRptPrice()).append("(红包金额) - ")
                    .append((orderSettleAccountOrder.getOrderCommissionFee()))
                    .append("(佣金金额) + ").append(orderSettleAccountOrder.getBaseMemberDiscount())
                    .append("(会员折扣) - ").append(0.00).append("(退单金额) - ").append(0.00).append("(退还红包金额) + ")
                    .append(0.00).append("(退还佣金) + ")
                    .append(orderSettleAccountOrder.getOrderShippingFee() - returnSettleAccountOrder.getReturnShippingFee())
                    .append("(运费) - ").append(0.00).append("(退还会员折扣) - ")
                    .append(orderSettleAccountOrder.getTgCommission()).append("(推广佣金) - ")
                    .append(orderSettleAccountOrder.getFxCommission()).append("(分享佣金)");
        }
        // 3、没有订单有退单的情况
        if (null == orderSettleAccountOrder && null != returnSettleAccountOrder) {
            totalAmount = totalAmount-returnSettleAccountOrder.getReturnCash()-(null == returnSettleAccountOrder.getReturnRptCash() ? 0.00
                    : returnSettleAccountOrder.getReturnRptCash())+returnSettleAccountOrder.getOrderReturnCommissionFee()-returnSettleAccountOrder.getReturnMemberDiscount();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ").append(0.00).append("(订单金额 不含运费) + ").append(0.00)
                    .append("(红包金额) - ").append(0.00).append("(佣金金额) + ").append(0.00).append("(会员折扣) - ")
                    .append(returnSettleAccountOrder.getReturnCash()).append("(退单金额) - ")
                    .append(null == returnSettleAccountOrder.getReturnRptCash() ? 0.00
                            : returnSettleAccountOrder.getReturnRptCash())
                    .append("(退还红包金额) + ").append(returnSettleAccountOrder.getOrderReturnCommissionFee())
                    .append("(退还佣金) + ")
                    .append(0.00).append("(运费) - ").append(returnSettleAccountOrder.getReturnMemberDiscount()).append("(退还会员折扣) - ")
                    .append(0.00).append("(推广佣金) - ")
                    .append(0.00).append("(分享佣金)");
        }
        // 4、有订单有退单的情况
        if (null != orderSettleAccountOrder && null != returnSettleAccountOrder) {
            totalAmount = totalAmount
                    + orderSettleAccountOrder.getOrderPaymentAmount()
                    +orderSettleAccountOrder.getOrderRptPrice()
                    -orderSettleAccountOrder.getOrderCommissionFee()
                    +orderSettleAccountOrder.getBaseMemberDiscount()
                    -returnSettleAccountOrder.getReturnCash()
                    -(null == returnSettleAccountOrder.getReturnRptCash() ? 0.00: returnSettleAccountOrder.getReturnRptCash())
                    -returnSettleAccountOrder.getReturnMemberDiscount()
                    + returnSettleAccountOrder.getOrderReturnCommissionFee()
                    - orderSettleAccountOrder.getTgCommission() - orderSettleAccountOrder.getFxCommission();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(new BigDecimal(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee())
                            .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()).append("(订单金额 不含运费) + ")
                    .append(orderSettleAccountOrder.getOrderRptPrice()).append("(红包金额) - ")
                    .append((orderSettleAccountOrder.getOrderCommissionFee())).append("(佣金金额) + ")
                    .append(orderSettleAccountOrder.getBaseMemberDiscount()).append("(会员折扣) - ")
                    .append(returnSettleAccountOrder.getReturnCash()).append("(退单金额) - ")
                    .append(null == returnSettleAccountOrder.getReturnRptCash() ? 0.00 : returnSettleAccountOrder.getReturnRptCash()).append("(退还红包金额) + ")
                    .append(returnSettleAccountOrder.getOrderReturnCommissionFee()).append("(退还佣金) + ")
                    .append(orderSettleAccountOrder.getOrderShippingFee() - returnSettleAccountOrder.getReturnShippingFee()).append("(运费) - ")
                    .append(returnSettleAccountOrder.getReturnMemberDiscount()).append("(退还会员折扣) - ")
                    .append(orderSettleAccountOrder.getTgCommission()).append("(推广佣金) - ")
                    .append(orderSettleAccountOrder.getFxCommission()).append("(分享佣金)");
        }

        result.setOsAmountStr(osAmountStr.toString());
        result.setBeformDate(beformDate);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult waitOrderList(WaitOrderDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        param.setShopId(shopId);
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(shopId,2);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        Page<OrderBaseListVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<OrderBaseListVO> orderList = this.baseMapper.selectWaitOrderList(page,param,dBefore);
        return ResponseResult.success(orderList);
    }

    @Override
    public ResponseResult waitFineList(PageUserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        param.setShopId(shopId);
        Page<FineBaseListVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<FineBaseListVO> fineList  = this.baseMapper.selectWaitFineList(page,param);
        return ResponseResult.success(fineList);
    }

    @Override
    public ResponseResult waitReturnList(WaitOrderDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        param.setShopId(shopId);
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(shopId,2);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        Page<ReturnBaseListVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<ReturnBaseListVO> returnList = this.baseMapper.selectWaitReturnList(page,param,dBefore,2);
        return ResponseResult.success(returnList);
    }

    @Override
    public ResponseResult waitDealerReturnList(WaitOrderDTO param) throws IllegalAccessException {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        param.setShopId(shopId);
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(shopId,2);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        Map data= ParseMapUtils.beanToMap(param);
        IPage<ReturnBaseListVO> page=this.baseMapper.selectWaitDealerReturnList(new Query<ReturnBaseListVO>().getPage(data),
                shopId, param,dBefore);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult getMerchantAmount(FinancialSettlementDTO param) throws IllegalAccessException {
        if (param.getStartTime() == "" && param.getEndTime() == "") {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String finishTime = dateformat.format(new Date());
            param.setEndTime(finishTime);
            param.setStartTime("2017-01-01");
        }
        Map data= ParseMapUtils.beanToMap(param);
        IPage<FinancialSettlementDTO> page=this.baseMapper.getMerchantAmount(new Query<FinancialSettlementDTO>().getPage(data),
                param);

        return ResponseResult.success(PageUtils.getPage(page));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateOrderSettlementByMap(Map<String, Object> map) {
        Integer count = this.baseMapper.updateOrderSettlementByMap(map);
        if (count > 0) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult platFormReturnorderinfoExcel(Map<String, Object> paraMap) {
        OrderSettlementEntity orderSettlementEntity = this.baseMapper.selectById(paraMap.get("orderSettlementId").toString());
        //如果时间在 2019-01-28 之前，则需要这个时间
        if (orderSettlementEntity.getOsDate() == null) {
            paraMap.put("osStartDate", orderSettlementEntity.getOsStartDate());
            paraMap.put("osEndDate", orderSettlementEntity.getOsEndDate());
            paraMap.remove("orderSettlementId");
            paraMap.put("returnShopHandle", "returnShopHandle");
        }
        paraMap.put("shopId", orderSettlementEntity.getShopId());
        paraMap.put("osDatetime", orderSettlementEntity.getOsDatetime());
        IPage<ReturnOrderDetailListVO> listReutrnOrderExport;
        if ("3".equals(orderSettlementEntity.getOsOrderType().toString())) {
            listReutrnOrderExport = this.baseMapper.listSupplyReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap), paraMap);
        } else if ("2".equals(orderSettlementEntity.getOsOrderType().toString())) {
            listReutrnOrderExport = this.baseMapper.listDealerReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap), paraMap);
        } else {
            listReutrnOrderExport = this.baseMapper.listReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap), paraMap);
        }
        String[] headers = {"订单编号", "退单编号", "退单金额（不含运费）", "退还佣金", "退还红包金额", "退还会员折扣", "退还经销折扣", "退还供货价",
                "退货日期", "退货完成日期", "退货理由", "买家"};

        List<ReturnOrderDetailListVO> records = listReutrnOrderExport.getRecords();
        List<Map<String, String>> list = Lists.newArrayList();
        for (ReturnOrderDetailListVO res : records) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();

            map.put("订单编号", res.getOrderId());
            map.put("退单编号", res.getReturnCode());
            map.put("退单金额（不含运费）", res.getReturnCash().toString());
            map.put("退还佣金", res.getReturnRptCash().toString());
            map.put("退还红包金额", res.getReturnMemberDiscount().toString());
            map.put("退还会员折扣", res.getReturnSupperDiscountFee().toString());
            map.put("退还经销折扣", res.getOrderReturnPrice().toString());
            map.put("退还供货价", res.getReturnAddTime());
            map.put("退货日期", DateUtils.formateForSdfCn(res.getReturnFinishTime()));
            map.put("退货理由", res.getReturnReason());
            map.put("买家", res.getBuyerUserAccount());
            list.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("合并数据", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult platFormReturnorderinfo(Map<String, Object> paraMap) {
        OrderSettlementEntity orderSettlementEntity = this.baseMapper.selectById(paraMap.get("orderSettlementId").toString());
        //如果时间在 2019-01-28 之前，则需要这个时间
        if (orderSettlementEntity.getOsDate() == null) {
            paraMap.put("osStartDate", orderSettlementEntity.getOsStartDate());
            paraMap.put("osEndDate", orderSettlementEntity.getOsEndDate());
            paraMap.remove("orderSettlementId");
            paraMap.put("returnShopHandle", "returnShopHandle");
        }
        paraMap.put("shopId", orderSettlementEntity.getShopId());
        IPage<ReturnOrderDetailListVO> page;
        if ("3".equals(orderSettlementEntity.getOsOrderType().toString())) {
            page = this.baseMapper.listSupplyReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap), paraMap);
        } else if ("2".equals(orderSettlementEntity.getOsOrderType().toString())) {
            page = this.baseMapper.listDealerReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap), paraMap);
        } else {
            page = this.baseMapper.listReutrnOrder(new Query<ReturnOrderDetailListVO>().getPage(paraMap), paraMap);
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult listBaseorderinfo(Map<String, Object> paraMap) {
        OrderSettlementEntity orderSettlementEntity = this.baseMapper.selectById(paraMap.get("orderSettlementId").toString());
        //如果时间在 2019-01-28 之前，则需要这个时间
        if (orderSettlementEntity.getOsDate() == null) {
            paraMap.put("osStartDate", orderSettlementEntity.getOsStartDate());
            paraMap.put("osEndDate", orderSettlementEntity.getOsEndDate());
            paraMap.remove("orderSettlementId");
        }
        paraMap.put("shopId", orderSettlementEntity.getShopId());
        paraMap.put("osDatetime", DateUtils.dateTime(orderSettlementEntity.getOsDatetime()));
        IPage<OrderBaseInfoVO> page;
        if ("3".equals(orderSettlementEntity.getOsOrderType().toString())) {
            page = this.baseMapper.listSupplyBaseInfo(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
        } else if ("2".equals(orderSettlementEntity.getOsOrderType().toString())) {
            page = this.baseMapper.listDealerBaseInfo(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
        } else {
            page = this.baseMapper.listBaseInfo(new Query<OrderBaseInfoVO>().getPage(paraMap), paraMap);
            List<OrderBaseInfoVO> records = page.getRecords();
            for (OrderBaseInfoVO orderBaseInfo : records) {
                BigDecimal b1 = new BigDecimal(orderBaseInfo.getOrderPaymentAmount().toString());
                BigDecimal b2 = new BigDecimal(orderBaseInfo.getOrderSupplyAmount().toString());
                orderBaseInfo.setOrderPaymentAmount(b1.subtract(b2).doubleValue());
            }
        }

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("listOrderBase", page);
        returnMap.put("osOrderAmount", orderSettlementEntity.getOsOrderAmount());
        return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult platFormSettlementdetail(Map<String, Object> paraMap) {
        OrderSettlementEntity orderSettlement = this.baseMapper.selectById(paraMap.get("osId").toString());
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("osId", orderSettlement.getOsId());
        returnMap.put("shopName", orderSettlement.getShopName());
        returnMap.put("date", orderSettlement.getOsStartDate());
        returnMap.put("osDatetime", orderSettlement.getOsDatetime());

        String osAmountDetail;
        if(orderSettlement.getOsOrderType().equals("2")){
            //订单金额（不含运费）-供货价-抽佣+会员折扣+退还抽佣-退单金额（不含运费）+供货价-退还会员折扣
            osAmountDetail = orderSettlement.getOsAmount() + " = "
                    + orderSettlement.getOsOrderAmount() + "(订单金额 不含运费) - "
                    + orderSettlement.getOsSupplyPrice() + "(供货价) - "
                    + orderSettlement.getOsCommisAmount() + "(佣金金额) + "
                    + orderSettlement.getOsBaseMemberDiscount() + "(会员折扣) + "
                    + orderSettlement.getOsCommisReturnAmount() + "(退还佣金) - "
                    + orderSettlement.getOsOrderReturnAmount() + "(退单金额) + "
                    + orderSettlement.getOsReturnSupplyPrice() + "(退还供货价) - "
                    + orderSettlement.getOsReturnMemberDiscount() + "(退还会员折扣)";
        }else if(orderSettlement.getOsOrderType().equals("3")){
            // 供应商结算单
            osAmountDetail = orderSettlement.getOsAmount() + " = " + orderSettlement.getOsOrderAmount() + "(供货价 不含运费) -"
                    + orderSettlement.getOsSupperDiscountFee() + "(经销折扣) - "
                    + orderSettlement.getOsCommisAmount() + "(佣金金额) -"
                    + orderSettlement.getOsOrderReturnAmount() + "(退还供货价) +  "
                    + orderSettlement.getOsCommisReturnAmount() + "(退还佣金) + "
                    + orderSettlement.getOsReturnSupperDiscountFee() + "(退还经销折扣) + "
                    + orderSettlement.getOsShippingAmount() + "(运费)" ;
        }else{
            BigDecimal osAmount = orderSettlement.getOsOrderAmount();
            osAmountDetail = orderSettlement.getOsAmount() + " = " + osAmount + "(订单金额 不含运费)" + " + "
                    + orderSettlement.getOsRedpacketAmount() + "(红包金额) - "
                    + orderSettlement.getOsCommisAmount() + "(佣金金额) + "
                    + orderSettlement.getOsBaseMemberDiscount() + "(会员折扣) - "
                    + orderSettlement.getOsOrderReturnAmount() + "(退单金额) - "
                    + orderSettlement.getOsRedpacketReturnAmount() + "(退还红包金额) + "
                    + orderSettlement.getOsCommisReturnAmount() + "(退还佣金) + "
                    + orderSettlement.getOsShippingAmount() + "(运费) - "
                    + orderSettlement.getOsReturnMemberDiscount() + "(退还会员折扣) - "
                    + orderSettlement.getOsTgCommission() + "(推广佣金) - "
                    + orderSettlement.getOsFxCommission() + "(分享佣金) ";
        }
        returnMap.put("osAmount", osAmountDetail);
        returnMap.put("osState", orderSettlement.getOsState());

        return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult queryPlatFormListSettlement(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        if (null != userInfo) {
            //分页查询数据
            IPage<PlatFormOrderSettlementVO> page = this.baseMapper.queryPlatFormListSettlement(new Query<PlatFormOrderSettlementVO>().getPage(map), map);

            return ResponseResult.success(PageUtils.getPage(page));
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryPlatFormListSettlementExcel(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        if (null != userInfo) {
            List<PlatFormOrderSettlementVO> page = this.baseMapper.queryPlatFormListSettlementExcel(map);
            String[] headers = {"账单编号", "订单金额(含运费)", "运费", "收取佣金", "退单金额", "退还佣金",
                    "店铺费用", "本期应结", "出账日期", "账单状态", "商家名称", "开始日期", "结束日期"};

            List<Map<String, String>> list = Lists.newArrayList();
            for (PlatFormOrderSettlementVO platFormOrderSettlement : page) {
                HashMap<String, String> mapExcel = Maps.newHashMap();
                mapExcel.put("账单编号", platFormOrderSettlement.getOsId());
                mapExcel.put("订单金额(含运费)", platFormOrderSettlement.getOsOrderAmount());
                mapExcel.put("运费", platFormOrderSettlement.getOsShippingAmount());
                mapExcel.put("收取佣金", platFormOrderSettlement.getOsCommisAmount());
                mapExcel.put("退单金额", platFormOrderSettlement.getOsOrderReturnAmount());
                mapExcel.put("退还佣金", platFormOrderSettlement.getOsCommisReturnAmount());
                mapExcel.put("店铺费用", platFormOrderSettlement.getOsShopCostAmount());
                mapExcel.put("本期应结", platFormOrderSettlement.getOsAmount());
                mapExcel.put("出账日期", platFormOrderSettlement.getOsDate().toString());
                mapExcel.put("账单状态", platFormOrderSettlement.getOsShopCostAmount());
                mapExcel.put("商家名称", platFormOrderSettlement.getShopName());
                mapExcel.put("开始日期", platFormOrderSettlement.getOsStartDate());
                mapExcel.put("结束日期", platFormOrderSettlement.getOsEndDate());
                list.add(mapExcel);
            }
            // excel文件名
            Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
             * 该list为每个sheet页的数据
             */> data = Maps.newHashMap();
            data.put("测试合并数据", list);
            String url = ExcelsUtil.createExcel(headers, data, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
            return ResponseResult.success(url);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }


    @Override
    public ResponseResult waitSupperReturnList(WaitOrderDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        String shopId = userInfo.getShopId();
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(shopId,2);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        Page<ReturnBaseListVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<ReturnBaseListVO> returnList = this.baseMapper.selectSupplyWaitReturnList(page,shopId,dBefore);
        return ResponseResult.success(PageUtils.getPage(returnList));
    }

    @Override
    public ResponseResult waitSupperOrderList(WaitOrderDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        String shopId = userInfo.getShopId();
        List<OrderBaseListVO> orderList;
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(shopId,2);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        // 供应商中心未结算业绩订单查询
        Page<OrderBaseListVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<OrderBaseListVO> returnList = this.baseMapper.selectSupplyWaitOrderList(page,shopId,dBefore);

        return ResponseResult.success(PageUtils.getPage(returnList));
    }

    @Override
    public ResponseResult supplyWaitSettlement(UserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        // 平台应付金额 =订单金额 - 佣金金额 - 经销商佣金 - 退单金额 + 退还佣金 + 经销退还佣金
        WaitSettlementVO result = new WaitSettlementVO();
        StringBuilder osAmountStr = new StringBuilder();
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(userInfo.getShopId(),null);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }
        // 获取单个店铺所有未结算的经销订单金额
        ShopSettleAccountInfoDTO orderSettleAccountOrder = this.baseMapper.getSupplySettleAccountOrder(userInfo.getShopId(),dBefore);
        // 获取单个店铺所有未结算的退单金额
        ShopSettleAccountInfoDTO returnSettleAccountOrder = this.baseMapper.getSupplySettleAccountReturn(userInfo.getShopId(),dBefore);
        if (null == orderSettleAccountOrder) {
            orderSettleAccountOrder = new ShopSettleAccountInfoDTO();
        }

        if (null == returnSettleAccountOrder) {
            returnSettleAccountOrder = new ShopSettleAccountInfoDTO();
        }
        Double totalAmount = 0.00;

        // 1、没有订单没有退单
        if (null == orderSettleAccountOrder && null == returnSettleAccountOrder) {
            //供货价+运费-抽佣-退单（供货价）+退还抽佣-经销商等级折扣+退还经销商等级折扣
            osAmountStr.append(totalAmount).append(" = ")
                    .append(0.00).append("(供货价 不含运费) - ")
                    .append(0.00).append("(经销折扣) - ")
                    .append(0.00).append("(佣金金额) - ")
                    .append(0.00).append("(退还供货价) + ")
                    .append(0.00).append("(退还佣金) + ")
                    .append(0.00).append("(退还经销折扣) + ")
                    .append(0.00).append("(运费) ");

        }

        // 2、有订单没有退单的情况
        if (null != orderSettleAccountOrder && null == returnSettleAccountOrder) {
            totalAmount = totalAmount + (orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee())
                    - orderSettleAccountOrder.getSupperDiscountFee()
                    - orderSettleAccountOrder.getOrderCommissionFee()
                    + orderSettleAccountOrder.getOrderShippingFee();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).append("(供货价 不含运费) - ")
                    .append(orderSettleAccountOrder.getSupperDiscountFee()).append("(经销折扣) - ")
                    .append(orderSettleAccountOrder.getOrderCommissionFee()).append("(佣金金额) - ")
                    .append(0.00).append("(退还供货价) + ")
                    .append(0.00).append("(退还佣金) + ")
                    .append(0.00).append("(退还经销折扣) + ")
                    .append(orderSettleAccountOrder.getOrderShippingFee()).append("(运费) ");
        }
        // 3、没有订单有退单的情况
        if (null == orderSettleAccountOrder && null != returnSettleAccountOrder) {
            totalAmount = totalAmount + (orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee())
                    - returnSettleAccountOrder.getReturnCash()
                    + returnSettleAccountOrder.getOrderReturnCommissionFee()
                    + returnSettleAccountOrder.getReturnSupperDiscountFee();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).append("(供货价 不含运费) - ")
                    .append(0.00).append("(经销折扣) - ")
                    .append(0.00).append("(佣金金额) - ")
                    .append(returnSettleAccountOrder.getReturnCash()).append("(退还供货价) + ")
                    .append(returnSettleAccountOrder.getOrderReturnCommissionFee()).append("(退还佣金) + ")
                    .append(returnSettleAccountOrder.getReturnSupperDiscountFee()).append("(退还经销折扣) + ")
                    .append(0.00).append("(运费) ");
        }
        // 4、有订单有退单的情况
        if (null != orderSettleAccountOrder && null != returnSettleAccountOrder) {
            totalAmount = totalAmount + (orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee())
                    - orderSettleAccountOrder.getOrderCommissionFee()
                    - returnSettleAccountOrder.getReturnCash()
                    + returnSettleAccountOrder.getOrderReturnCommissionFee()
                    + orderSettleAccountOrder.getOrderShippingFee();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).append("(供货价 不含运费) - ")
                    .append(orderSettleAccountOrder.getOrderCommissionFee()).append("(佣金金额) - ")
                    .append(returnSettleAccountOrder.getReturnCash()).append("(退还供货价) + ")
                    .append(returnSettleAccountOrder.getOrderReturnCommissionFee()).append("(退还佣金) + ")
                    .append(orderSettleAccountOrder.getOrderShippingFee()).append("(运费) ");
        }

        result.setOsAmountStr(osAmountStr.toString());
        result.setBeformDate(beformDate);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult waitDealerOrderList(WaitOrderDTO param) throws IllegalAccessException {

        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        if(null == userInfo.getShopId()){
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        param.setShopId(shopId);
        // 获取上次结算时间
        Date beformDate = this.baseMapper.getBeformDate(userInfo.getShopId(),2);
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dBefore = df.parse("2019-04-10 00:00:00");
            } catch (ParseException e) {
            }
        }else{
            dBefore = beformDate;
        }

        Map data= ParseMapUtils.beanToMap(param);
        IPage<OrderBaseListVO> page=this.baseMapper.selectWaitDealerOrderList(new Query<OrderBaseListVO>().getPage(data),
                                param,dBefore);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult dealerWaitSettlement(Map<String, Object> map) {
        // 平台应付金额 =订单金额 - 佣金金额 - 经销商佣金 - 退单金额 + 退还佣金 + 经销退还佣金
        Map<String, Object> result = new HashMap<>();
        StringBuilder osAmountStr = new StringBuilder();
        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(map.get("token").toString());

        Date beformDate = this.baseMapper.getBeformDate(userInfo.getShopId(),2); // 获取上次结算时间
        Date dBefore = null;
        if(null == beformDate){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            try {
                dBefore = df.parse("2019-04-10");

            } catch (ParseException e) {
                return ResponseResult.fail(e.getMessage());
            }
        }else{
            dBefore = beformDate;
        }
        // 获取单个店铺所有未结算的经销订单金额
        ShopSettleAccountInfoDTO orderSettleAccountOrder = this.baseMapper.getSettleDealerAccountOrder(Integer.valueOf(userInfo.getShopId()), dBefore);
        // 获取单个店铺所有未结算的退单金额
        ShopSettleAccountInfoDTO returnSettleAccountOrder = this.baseMapper.getSettleDealerAccountReturn(Integer.valueOf(userInfo.getShopId()), dBefore);

        if(null == orderSettleAccountOrder){
            orderSettleAccountOrder = new ShopSettleAccountInfoDTO();
        }

        if(null == returnSettleAccountOrder){
            returnSettleAccountOrder = new ShopSettleAccountInfoDTO();
        }

        Double totalAmount = 0.00;
        // 1、没有订单没有退单
        if (null == orderSettleAccountOrder && null == returnSettleAccountOrder) {
            //订单金额（不含运费）-供货价-抽佣+会员折扣+退还抽佣-退单金额（不含运费）+供货价-退还会员折扣
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            osAmountStr.append(totalAmount).append(" = ")
                    .append(0.00).append("(订单金额 不含运费) - ")
                    .append(0.00).append("(供货价) - ")
                    .append(0.00).append("(佣金金额) + ")
                    .append(0.00).append("(会员折扣) + ")
                    .append(0.00).append("(退还佣金) - ")
                    .append(0.00).append("(退单金额) + ")
                    .append(0.00).append("(退还供货价) - ")
                    .append(0.00).append("(退还会员折扣)");
        }

        // 2、有订单没有退单的情况
        if (null != orderSettleAccountOrder && null == returnSettleAccountOrder) {
            //订单金额（不含运费）-供货价-抽佣+会员折扣+退还抽佣-退单金额（不含运费）+供货价-退还会员折扣
            totalAmount = totalAmount
                    + (orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee() )
                    - orderSettleAccountOrder.getSupperPriceSum()
                    - orderSettleAccountOrder.getOrderCommissionFee()
                    + orderSettleAccountOrder.getBaseMemberDiscount();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).append("(订单金额 不含运费) - ")
                    .append(orderSettleAccountOrder.getSupperPriceSum()).append("(供货价) - ")
                    .append(orderSettleAccountOrder.getOrderCommissionFee()).append("(佣金金额) + ")
                    .append(orderSettleAccountOrder.getBaseMemberDiscount()).append("(会员折扣) + ")
                    .append(0.00).append("(退还佣金) - ")
                    .append(0.00).append("(退单金额) + ")
                    .append(0.00).append("(退还供货价) - ")
                    .append(0.00).append("(退还会员折扣)");
        }
        // 3、没有订单有退单的情况
        if (null == orderSettleAccountOrder && null != returnSettleAccountOrder) {
            //订单金额（不含运费）-供货价-抽佣+会员折扣+退还抽佣-退单金额（不含运费）+供货价-退还会员折扣
            totalAmount = totalAmount
                    + (orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee() )
                    + returnSettleAccountOrder.getOrderReturnCommissionFee()
                    - returnSettleAccountOrder.getReturnCash()
                    + returnSettleAccountOrder.getSupperReturnPrice()
                    - returnSettleAccountOrder.getReturnMemberDiscount();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).append("(订单金额 不含运费) - ")
                    .append(0.00).append("(供货价) - ")
                    .append(0.00).append("(佣金金额) + ")
                    .append(0.00).append("(会员折扣) + ")
                    .append(returnSettleAccountOrder.getOrderReturnCommissionFee()).append("(退还佣金) - ")
                    .append(returnSettleAccountOrder.getReturnCash()).append("(退单金额) + ")
                    .append(returnSettleAccountOrder.getSupperReturnPrice()).append("(退还供货价) - ")
                    .append(returnSettleAccountOrder.getReturnMemberDiscount()).append("(退还会员折扣)");
        }
        // 4、有订单有退单的情况
        if (null != orderSettleAccountOrder && null != returnSettleAccountOrder) {
            //订单金额（不含运费）-供货价-抽佣+会员折扣+退还抽佣-退单金额（不含运费）+供货价-退还会员折扣
            totalAmount = totalAmount
                    + (orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee() )
                    - orderSettleAccountOrder.getSupperPriceSum()
                    - orderSettleAccountOrder.getOrderCommissionFee()
                    + orderSettleAccountOrder.getBaseMemberDiscount()
                    + returnSettleAccountOrder.getOrderReturnCommissionFee()
                    - returnSettleAccountOrder.getReturnCash()
                    + returnSettleAccountOrder.getSupperReturnPrice()
                    - returnSettleAccountOrder.getReturnMemberDiscount();
            //四舍五入
            BigDecimal bg = new BigDecimal(totalAmount);
            totalAmount= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            osAmountStr.append(totalAmount).append(" = ")
                    .append(orderSettleAccountOrder.getOrderPaymentAmount() - orderSettleAccountOrder.getOrderShippingFee()).append("(订单金额 不含运费) - ")
                    .append(orderSettleAccountOrder.getSupperPriceSum()).append("(供货价) - ")
                    .append(orderSettleAccountOrder.getOrderCommissionFee()).append("(佣金金额) + ")
                    .append(orderSettleAccountOrder.getBaseMemberDiscount()).append("(会员折扣) + ")
                    .append(returnSettleAccountOrder.getOrderReturnCommissionFee()).append("(退还佣金) - ")
                    .append(returnSettleAccountOrder.getReturnCash()).append("(退单金额) + ")
                    .append(returnSettleAccountOrder.getSupperReturnPrice()).append("(退还供货价) - ")
                    .append(returnSettleAccountOrder.getReturnMemberDiscount()).append("(退还会员折扣)");
        }

        result.put("osAmountStr",osAmountStr.toString());
        result.put("beformDate",beformDate);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult confirmSettlement(Map<Object, Object> map) {
        String token = map.get("token").toString();
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(token);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        UserInfoVO ui = JSON.parseObject(JSON.toJSONString(rr.getData()), UserInfoVO.class);
        String shopId = ui.getShopId();
        // 结算编号
        String settlementId = (String) map.get("settlementId");
        // 结算金额
        String settlementMoney = map.get("settlementMoney") + "";

        Map<String, String> paraMap = new HashMap<>(8);
        paraMap.put("osId", settlementId);
        OrderSettlementEntity orderSettlementEntity = this.baseMapper.selectById(settlementId);

        Map<String, Object> settlementMap = new HashMap<>();
        settlementMap.put("token", token);
        settlementMap.put("settlementId", settlementId);
        settlementMap.put("settlementMoney", settlementMoney);
        settlementMap.put("settlementType", orderSettlementEntity.getOsOrderType());
        if (payMentServiceClient.insertSettlementRecord(settlementMap)) {
            this.baseMapper.updateSettlementOrder(settlementId, Integer.valueOf(shopId));
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.BALANCE_NOT_ENOUGH_ERROR);
    }
}




